package com.ruoyi.framework.aspectj;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.annotation.EasyCacheClear;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 自定缓存清除切面
 *
 * 
 * @date 2022/8/21 21:16
 */
@Aspect
@Component
public class EasyCacheClearAspect {

    /**
     * 日志记录
     */
    private static Logger logger = LoggerFactory.getLogger(EasyCacheClearAspect.class);

    @Autowired
    private RedisCache redisCache;

    @Pointcut("@annotation(com.ruoyi.common.annotation.EasyCacheClear)"
            + "|| @within(com.ruoyi.common.annotation.EasyCacheClear)")
    public void dsPointCut() {

    }

    /**
     * 根据
     *
     * 
     * @date 2022/10/13 18:05
     * @param point
     * @return
     */
    @After("dsPointCut()")
    public void afterMethod(JoinPoint point) {
        logger.info("进入自定义缓存清除切面。" + DateUtils.getTime());
        MethodSignature signature = (MethodSignature) point.getSignature();
        EasyCacheClear easyCacheClear = AnnotationUtils.findAnnotation(signature.getMethod(), EasyCacheClear.class);
        //  进入缓存清除切面
        // 若缓存参数为空，直接返回
        if (easyCacheClear == null || StringUtils.isBlank(easyCacheClear.cacheNamePrefix()[0])) {
            logger.info("缓存参数为空，直接返回。" + DateUtils.getTime());
            return;
        }

        // 根据缓存名称前缀查询所有的缓存名称
        String[] cacheNamePrefix = easyCacheClear.cacheNamePrefix();
        for (String namePrefix : cacheNamePrefix) {
            Collection<String> keys = redisCache.keys(namePrefix + ":*");
            Collection<String> keys1 = redisCache.keys(namePrefix);
            if (keys != null) {
                keys.addAll(keys1);
            } else {
                keys = keys1;
            }
            if (CollUtil.isNotEmpty(keys)) {
                // 删除缓存名称
                try {
                    redisCache.deleteObject(keys);
                } catch (Exception e) {
                    logger.error("删除缓存异常！", e);
                }
                logger.info("删除缓存记录条数：" + keys.size() + ",缓存key为：" + namePrefix + "。" + DateUtils.getTime());
            }
        }
        logger.info("自定义缓存清除切面完成。" + DateUtils.getTime());
    }

}
